/**
 * 语音模块，负责处理单词发音和例句发音
 */
import { ref } from 'vue';

export const useSpeechModule = (wordData) => {
  // 跟踪当前是否正在播放语音
  const isPlaying = ref(false);
  // 存储预加载的语音
  const preloadedUtterances = new Map();
  // 当前正在播放的语音
  let currentUtterance = null;

  /**
   * 预加载单词发音
   * @param {Object} word - 单词对象
   */
  const preloadPronunciation = (word) => {
    if (!word?.content || !('speechSynthesis' in window)) return;
    
    // 预加载美式发音
    const usUtterance = createUtterance(word.content, 'en-US');
    preloadedUtterances.set(`${word.content}_us`, usUtterance);
    
    // 预加载英式发音
    const ukUtterance = createUtterance(word.content, 'en-GB');
    preloadedUtterances.set(`${word.content}_uk`, ukUtterance);
    
    // 如果有例句，也预加载
    if (word.example?.text) {
      const exampleUtterance = createUtterance(word.example.text, 'en-US');
      preloadedUtterances.set(`example_${word.content}`, exampleUtterance);
    }
  };

  /**
   * 创建语音合成对象
   * @param {string} text - 要播放的文本
   * @param {string} lang - 语言代码
   * @returns {SpeechSynthesisUtterance} 语音合成对象
   */
  const createUtterance = (text, lang = 'en-US') => {
    if (!text || !('speechSynthesis' in window)) return null;
    
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.lang = lang;
    
    const voices = window.speechSynthesis.getVoices();
    let preferredVoice;
    
    if (lang === 'en-GB') {
      // 寻找英式女声，然后是任何英式声音
      preferredVoice = voices.find(v => v.lang.includes('en-GB') && v.name.includes('Female')) ||
                      voices.find(v => v.lang.includes('en-GB'));
    } else {
      // 寻找美式女声，然后是任何美式声音
      preferredVoice = voices.find(v => v.lang.includes('en-US') && v.name.includes('Female')) ||
                      voices.find(v => v.lang.includes('en-US'));
    }
    
    // 如果找不到特定口音的声音，使用任何英语声音
    if (preferredVoice) {
      utterance.voice = preferredVoice;
    } else {
      const anyEnglishVoice = voices.find(v => v.lang.includes('en'));
      if (anyEnglishVoice) utterance.voice = anyEnglishVoice;
    }
    
    Object.assign(utterance, {
      volume: 1,
      rate: 0.9,
      pitch: 1
    });
    
    // 添加事件监听器以跟踪播放状态
    utterance.onend = () => {
      isPlaying.value = false;
      currentUtterance = null;
    };
    
    utterance.onerror = () => {
      isPlaying.value = false;
      currentUtterance = null;
    };
    
    return utterance;
  };

  /**
   * 播放单词发音
   * @param {string} accent - 发音口音类型，'us'或'uk'
   */
  const playPronunciation = (accent = 'us') => {
    if (!wordData.currentWord?.content || isPlaying.value) return;
    
    // 如果已经在播放，先取消当前播放
    cancelCurrentSpeech();
    
    const utteranceKey = `${wordData.currentWord.content}_${accent}`;
    let utterance = preloadedUtterances.get(utteranceKey);
    
    if (!utterance) {
      // 如果没有预加载，创建新的语音合成对象
      utterance = createUtterance(
        wordData.currentWord.content, 
        accent === 'uk' ? 'en-GB' : 'en-US'
      );
    }
    
    if (utterance) {
      isPlaying.value = true;
      currentUtterance = utterance;
      window.speechSynthesis.speak(utterance);
    }
  };
  
  /**
   * 播放例句
   */
  const playExampleSentence = () => {
    if (isPlaying.value) return;
    
    const text = wordData.currentWord?.example?.text;
    if (!text) return;
    
    // 如果已经在播放，先取消当前播放
    cancelCurrentSpeech();
    
    const utteranceKey = `example_${wordData.currentWord.content}`;
    let utterance = preloadedUtterances.get(utteranceKey);
    
    if (!utterance) {
      utterance = createUtterance(text);
    }
    
    if (utterance) {
      isPlaying.value = true;
      currentUtterance = utterance;
      window.speechSynthesis.speak(utterance);
    }
  };
  
  /**
   * 播放相关单词
   * @param {string} word - 要播放的单词
   */
  const playRelatedWord = (word) => {
    if (isPlaying.value || !word) return;
    
    // 如果已经在播放，先取消当前播放
    cancelCurrentSpeech();
    
    const utterance = createUtterance(word);
    
    if (utterance) {
      isPlaying.value = true;
      currentUtterance = utterance;
      window.speechSynthesis.speak(utterance);
    }
  };
  
  /**
   * 通用语音播放函数
   * @param {string} text - 要播放的文本
   */
  const playSpeech = (text) => {
    if (!text || !('speechSynthesis' in window) || isPlaying.value) return;
    
    // 如果已经在播放，先取消当前播放
    cancelCurrentSpeech();
    
    const utterance = createUtterance(text);
    
    if (utterance) {
      isPlaying.value = true;
      currentUtterance = utterance;
      window.speechSynthesis.speak(utterance);
    }
  };
  
  /**
   * 取消当前正在播放的语音
   */
  const cancelCurrentSpeech = () => {
    if (window.speechSynthesis) {
      window.speechSynthesis.cancel();
    }
    isPlaying.value = false;
    currentUtterance = null;
  };

  return {
    playPronunciation,
    playExampleSentence,
    playRelatedWord,
    playSpeech,
    preloadPronunciation,
    cancelCurrentSpeech,
    isPlaying
  };
}; 